package com.qdlc.p2p.biz.service.impl;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.qdlc.p2p.biz.service.GoodsCategoryService;
import com.qdlc.p2p.common.exception.BusinessException;
import com.qdlc.p2p.common.exception.ScoreException;
import com.qdlc.p2p.common.util.DateUtil;
import com.qdlc.p2p.common.util.StringUtil;
import com.qdlc.p2p.dal.common.model.jpa.OrderFilter.OrderType;
import com.qdlc.p2p.dal.common.model.jpa.QueryParam;
import com.qdlc.p2p.dal.common.model.jpa.SearchFilter.Operators;
import com.qdlc.p2p.dal.dao.GoodsCategoryDao;
import com.qdlc.p2p.dal.dto.GoodsCategory;
import com.qdlc.p2p.dal.model.GoodsCategoryModel;

@Service("goodsCategoryService")
public class GoodsCategoryServiceImpl implements GoodsCategoryService {

	@Resource
	private GoodsCategoryDao goodsCategoryDao;
	
	@Override
	public List<GoodsCategory> list() {
		QueryParam param = QueryParam.getInstance();
		param.addOrder(OrderType.ASC, "sort");
		return goodsCategoryDao.findByCriteria(param);
	}

	@Override
	public List<GoodsCategory> enableList() {
		QueryParam param = QueryParam.getInstance();
		param.addParam("status", GoodsCategoryModel.STATUS_ENABLE);
		param.addOrder(OrderType.ASC, "sort");
		return goodsCategoryDao.findByCriteria(param);
	}

	@Override
	public List<GoodsCategory> getCategoryList(GoodsCategoryModel model) {
		QueryParam param = QueryParam.getInstance();
		if (StringUtil.isNotBlank(model.getSearchName())) {// 模糊查询
			param.addParam("name", Operators.LIKE, model.getSearchName().trim());
		} else {// 精确查询
			if (StringUtil.isNotBlank(model.getName())) {
				param.addParam("name", Operators.LIKE, model.getName().trim());
			}
			if (model.getStatus() != 99){
				param.addParam("status", model.getStatus());
			}
			if (StringUtil.isNotBlank(model.getStartTime())) {
				Date start = DateUtil.valueOf(model.getStartTime() + " 00:00:00");
				param.addParam("addTime", Operators.GTE, start);
			}
			if (StringUtil.isNotBlank(model.getEndTime())) {
				Date end = DateUtil.valueOf(model.getEndTime() + " 23:59:59");
				param.addParam("addTime", Operators.LTE, end);
			}
		}
		param.addOrder(OrderType.DESC, "id");
		return goodsCategoryDao.findByCriteria(param);
	}

	@Override
	public void save(GoodsCategory goodsCategory) {
		goodsCategory.setAddTime(DateUtil.getNow());
		goodsCategoryDao.save(goodsCategory);
	}

	@Override
	public GoodsCategory find(long id) {
		return goodsCategoryDao.find(id);
	}

	@Override
	public void update(GoodsCategory goodsCategory) {
		goodsCategoryDao.update(goodsCategory);
	}

	@Override
	public void checkCategoryName(String name) {
		QueryParam param = QueryParam.getInstance();
		param.addParam("name", name.trim());
		List<GoodsCategory> list = goodsCategoryDao.findByCriteria(param);
		if (list.size() > 0) {
			throw new ScoreException("该类型名称已存在", BusinessException.TYPE_JSON);
		}
	}

}
